import * as zrender from 'zrender';
import { halfUnitWidth, timeScaleHeight, unitWidth } from '../../config';
import { isHoliday } from '../../utils/holiday';
import { hachureLines } from './hachure';
import { useCalendarStore } from '../../../stores/calendar';

/**
 * 绘制垂直网格线
 * @param {object} zr ZRender实例
 * @param {object} chartState 图表状态对象
 */
export function drawVerticalGridLines(
  zr: any,
  chartState: ChartState,
) {
  const calendarStore = useCalendarStore();
  const startDate = new Date(calendarStore.dateRange.start);
  const endDate = new Date(calendarStore.dateRange.end);

  // 计算总天数（包含开始和结束日期）
  const totalDays = Math.floor((+endDate - +startDate) / (60 * 60 * 24 * 1000)) + 1;

  const gridStartX = chartState.chartStartX;
  const gridLineCount = chartState.timeScaleUnits + 1;
  const deltaScrollX = Math.floor(chartState.lastScrollX / unitWidth);

  // 注意：i <= totalDays，确保最后一列线和最后一天的日期都能显示
  for (let i = 0 + deltaScrollX, count = 0; count < gridLineCount && i <= totalDays; i++, count++) {
    if (i > totalDays) {
      break;
    }
    const gridX = gridStartX + i * unitWidth;
    const gridLine = new zrender.Line({
      shape: {
        x1: gridX,
        y1: 0,
        x2: gridX,
        y2: chartState.canvasHeight,
      },
      style: {
        stroke: '#e0e0e0',
        lineWidth: 1,
      },
      silent: true,
    });
    // 日期文字和斜线只绘制到最后一天（i < totalDays）
    if (i < totalDays) {
      drawDateText(zr, i, gridX, startDate);
      drawHolidayHachure(zr, i, chartState, startDate);
    }
    zr.add(gridLine);
  }
}

/**
 * 绘制日期文字
 * @param {object} zr ZRender实例
 * @param {number} i 日期索引
 * @param {number} gridX 网格X坐标
 * @param {Date} startDate 开始日期
 */
function drawDateText(zr: any, i: number, gridX: number, startDate: Date) {
  const currentDate = new Date(+startDate + i * 60 * 60 * 24 * 1000);
  const dateInfo = isHoliday(currentDate);

  const dateText = new zrender.Text({
    style: {
      text: dateInfo.dateString,
      x: gridX + halfUnitWidth,
      y: timeScaleHeight / 2,
      align: 'center',
      verticalAlign: 'middle',
      fontSize: 12,
      fill: '#333',
    },
    z: 1,
  });

  zr.add(dateText);
}

/**
 * 绘制休息日斜线
 * @param {object} zr ZRender实例
 * @param {number} i 日期索引
 * @param {object} chartState 图表状态对象
 * @param {Date} startDate 开始日期
 */
function drawHolidayHachure(zr: any, i: number, chartState: ChartState, startDate: Date) {
  const currentDate = new Date(+startDate + i * 60 * 60 * 24 * 1000);
  const dateInfo = isHoliday(currentDate);

  if (dateInfo.isHoliday) {
    try {
      const lines = hachureLines([
        [chartState.chartStartX + i * unitWidth, chartState.chartStartY],
        [chartState.chartStartX + i * unitWidth + unitWidth, chartState.chartStartY],
        [chartState.chartStartX + i * unitWidth + unitWidth, chartState.canvasHeight],
        [chartState.chartStartX + i * unitWidth, chartState.canvasHeight],
      ], 10, 45);

      lines.forEach(line => {
        const [x1, y1] = line[0];
        const [x2, y2] = line[1];
        const l = new zrender.Line({
          shape: {
            x1,
            y1,
            x2,
            y2,
          },
          style: {
            stroke: 'rgba(221, 221, 221, 0.7)',
          },
        });
        zr.add(l);
      });
    } catch (error) {
      console.log('🚀 ~ drawHolidayHachure ~ error:', error);
    }
  }
}
